import { PrismaClient } from '@prisma/client'
import { logger } from '../utils/logger'

// 创建 Prisma 客户端实例
const prisma = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
    {
      emit: 'event',
      level: 'error',
    },
    {
      emit: 'event',
      level: 'info',
    },
    {
      emit: 'event',
      level: 'warn',
    },
  ],
})

// 监听 Prisma 事件
prisma.$on('query', (e: any) => {
  logger.debug('Query: ' + e.query)
  logger.debug('Params: ' + e.params)
  logger.debug('Duration: ' + e.duration + 'ms')
})

prisma.$on('error', (e: any) => {
  logger.error('Prisma error:', e)
})

prisma.$on('info', (e: any) => {
  logger.info('Prisma info:', e.message)
})

prisma.$on('warn', (e: any) => {
  logger.warn('Prisma warning:', e.message)
})

// 数据库连接函数
export const connectDatabase = async (): Promise<void> => {
  try {
    await prisma.$connect()
    logger.info('✅ Database connected successfully')
  } catch (error) {
    logger.error('❌ Database connection failed:', error)
    process.exit(1)
  }
}

// 数据库断开连接函数
export const disconnectDatabase = async (): Promise<void> => {
  try {
    await prisma.$disconnect()
    logger.info('Database disconnected')
  } catch (error) {
    logger.error('Error disconnecting from database:', error)
  }
}

// 导出 Prisma 客户端
export { prisma }
export default prisma